<?php
namespace mz\controllers;

use Yii;
use yii\web\BadRequestHttpException;
use \yii\web\Controller as BaseController;

abstract class DashController extends BaseController
{
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            call_user_func_array([$this, 'initAction'], func_get_args());
            foreach($this->preFilters($action->id) as $filter) {
                $method = 'filter'.ucfirst($filter);
                if (method_exists($this, $method)) {
                    $return = $this->$method($action->id);
                    if (!$return){
                        throw new \Exception("$method is Invalid");
                    }
                } else {
                    throw new BadRequestHttpException(Yii::t('yii', 'Invalid filter name "{filter}".', [
                        'filter' => $filter,
                    ]));
                }
            }
            return true;
        }
    }

    public function initAction($action)
    {
        return true;
    }

    protected function preFilters($actionId)
    {
        return [];
    }

    public function ajaxReturn($array)
    {
        echo json_encode($array,JSON_UNESCAPED_UNICODE);
        Yii::$app->end();
    }
}